package com.ruoyi.web.controller.system;

import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RestTemplateConfig;
import com.ruoyi.common.config.WxAppConfig;
import com.ruoyi.common.core.domain.model.WxLoginBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private WxAppConfig wxAppConfig;

    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody WxLoginBody wxLoginBody) {

        String code = wxLoginBody.getCode();
        String phoneCode = wxLoginBody.getPhoneCode();

        log.info("code:" + code);
        log.info("phoneCode:" + code);

        // 向微信服务器发送请求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppConfig.getAppId() + "&secret=" + wxAppConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";

        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        log.info("微信返回结果：" + jsonObject.toJSONString());

        // 获取 session_key 和 openid
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        log.info("微信返回结果session_key：" + sessionKey);
        log.info("微信返回结果openid：" + openid);
        String phoneNumber = null;
        try {
            phoneNumber = getPhoneNumber(phoneCode);
        } catch (Exception e) {
            log.info("获取手机信息失败：" + e.getMessage());
        }
        log.info("微信返回结果phoneNumber：" + phoneNumber);
        if (sessionKey == null || openid == null) {
            // 打印微信返回的错误信息
            String errCode = jsonObject.getString("errcode");
            String errMsg = jsonObject.getString("errmsg");
            System.out.println("微信返回错误：errcode=" + errCode + ", errmsg=" + errMsg);
            log.error("微信返回错误：errcode=" + errCode + ", errmsg=" + errMsg);
            return AjaxResult.error("微信登录失败！");
        } else {
            String token = loginService.wxLogin(openid, phoneNumber);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("openid", openid);
            ajax.put("session_key", sessionKey);
            ajax.put("phoneNumber", phoneNumber);
            ajax.put(Constants.TOKEN, token);
            log.info("登录成功 ajax： " + token);
            log.info("登录成功 token： " + token);
            System.out.println("登录成功");
            log.info("登录成功");
            return ajax;
        }

    }


//    @PostMapping("/wxLogin")
//    public AjaxResult wxLogin(@RequestBody WxLoginBody wxLoginBody) throws Exception {
//
//        String code = wxLoginBody.getCode();
//
//        System.out.println("code:" + code);
//        log.info("code:" + code);
//
//
//        System.out.println("wxLoginBody:" + code);
//        log.info("wxLoginBody:" + code);
//
//        String JsonObject = getAccessToken();
//        JSONObject jsonObject = JSONObject.parseObject(JsonObject);
//        String accessToken = jsonObject.getString("access_token");
//        String userPhoneNumber = getUserPhoneNumber(code, accessToken);
//        JSONObject userPhoneNumberJson = JSONObject.parseObject(userPhoneNumber);
//        JSONObject phoneInfo = userPhoneNumberJson.getJSONObject("phone_info");
//        String phoneNumber = phoneInfo.getString("phoneNumber");
//
//
//        log.info("jsonObject:" + JsonObject);
//        log.info("accessToken:" + accessToken);
//        log.info("userPhoneNumber:" + userPhoneNumber);
//        log.info("phoneInfo:" + phoneInfo);
//        log.info("phoneNumber:" + phoneNumber);
//
//
//        if (accessToken == null || phoneNumber == null) {
//            String errCode = userPhoneNumberJson.getString("errcode");
//            String errMsg = userPhoneNumberJson.getString("errmsg");
//            System.out.println("微信返回错误：errcode=" + errCode + ", errmsg=" + errMsg);
//            log.error("微信返回错误：errcode=" + errCode + ", errmsg=" + errMsg);
//            return AjaxResult.error("微信登录失败！");
//        } else {
//            String token = loginService.wxLoginByPhoneNumber(phoneNumber);
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("phoneNumber", phoneNumber);
//            ajax.put(Constants.TOKEN, token);
//            log.info("登录成功 ajax： " + token);
//            log.info("登录成功 token： " + token);
//            System.out.println("登录成功");
//            log.info("登录成功");
//            return ajax;
//        }
//
//    }


    public String getAccessToken() throws Exception {

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxAppConfig.getAppId() + "&secret=" + wxAppConfig.getAppSecret();
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        // Read the response
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();
        log.info("获取access_token content   203行: " + content.toString());
        // Parse JSON to get access_token
        return content.toString();
    }

    public static String getUserPhoneNumber(String code, String accessToken) throws Exception {
        String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setDoOutput(true);
        // 构建请求体
        String requestBody = "{\"code\":\"" + code + "\"}";
        // 发送请求体
        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(requestBody);
            writer.flush();
        }
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();
        // 返回响应内容
        return content.toString();
    }


    public String getPhoneNumber(String code) throws Exception {
        String JsonObject = getAccessToken();
        JSONObject jsonObject = JSONObject.parseObject(JsonObject);
        String accessToken = jsonObject.getString("access_token");
        String userPhoneNumber = getUserPhoneNumber(code, accessToken);
        JSONObject userPhoneNumberJson = JSONObject.parseObject(userPhoneNumber);
        JSONObject phoneInfo = userPhoneNumberJson.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getString("phoneNumber");
        return phoneNumber;
    }


    /**
     * AES解密
     */
    private String decrypt(String sessionKey, String encryptedIv, String encryptedData) throws Exception {
        // 转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 如果密钥不足16位，那么就补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }
        // 如果初始向量不足16位，也补足
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            //            logger.info("解析错误");
            e.printStackTrace();
        }

        // 解析加密后的字符串
        return resultStr;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        user.setOpenId(loginUser.getOpenId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!Objects.equals(loginUser.getPermissions(), permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();

        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
